import { ref, computed, reactive } from "vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import i18n from "@/i18n";

const langs = reactive(Object.keys(i18n.global.messages.value));
export const typeTree = ref([]);
export const twoList = computed(
  () =>
    typeTree?.value?.find((v) => v.id === formData.skuClassify1Id)?.children ||
    []
);

export const typeLabels = computed(() => {
  let arr = [];
  const item1 = typeTree.value.find((v) => v.id === formData.skuClassify1Id);
  item1 && arr.push(item1);
  const item2 =
    item1?.children?.find((v) => v.id === formData.skuClassify2Id) || "";
  item2 && arr.push(item2);
  console.log("arr===", arr);

  return arr;
});

export const releaseStore = reactive({
  step: 0,
});

const formData = reactive({
  id: null,
  skuClassify1Id: "",
  skuClassify2Id: "",
  tenantId: "",
  attrs: [],
  image: "",
  bannerImages: [],
  isFree: 0,
  postage: 0,
  video: [],
});
langs.forEach((item) => {
  formData["name" + item] = "";
  formData["deliveryDetail" + item] = "";
  formData["content" + item] = "";
});
export { formData };
export const sku = ref({});
export const specList = ref([]);
export const useImageIndex = ref(0);
export const specDataList = ref([]); // 规格数据列表（价格，库存，重量等信息）
export const releaseLoading = ref(false);
export const loading = ref(false);
export const flag = ref(""); //默认选中的规格id
export const release = (router) => {
  releaseLoading.value = true;
  const specs = specList.value.map((v, index) => {
    return {
      details: v.info.map((v2) => ({
        specificationDetailId: v2.id,
        image: Array.isArray(v2.images) ? v2.images?.[0] : v2.images ?? ""
      })),
      specificationId: v.value,
      setImage: index === useImageIndex.value ? 1 : 0,
    };
  });
  const stocks = specDataList.value.map((v) => {
    const list = [];
    for (const key in v) {
      if (key.includes("spec_")) {
        list.push({
          specificationId: key.split("_")[1], //规格id
          specificationDetailId: v[key]?.id ?? "", //规格值id
        });
      }
    }
    return {
      skuSpecDetail: list,
      stock: v.stock, //库存
      price: v.price, //价格
      status: 1, //状态 0停用 1启用
      flag: flag.value === v.id ? 1 : 0, //标志 1默认选中
      itemCode: v.itemCode, //货号
      originalPrice: v.originalPrice,
    };
  });
  let params = {
    id: formData.id,
    stocks,
    specs,
    attrs: formData.attrs?.map((v) => ({ attributeId: v })),
    skuClassify1Id: formData.skuClassify1Id, //商品分类id
    skuClassify2Id: formData.skuClassify2Id, //商品分类id
    image: formData.image ?? "", //封面图
    video: formData.video?.[0]?.url ?? "", //视频
    bannerImages: formData.bannerImages?.join(","), //轮播图
    postage: formData.postage, //邮费
    tenantId: formData.tenantId, //商户ID
  };
  langs.forEach((item) => {
    params["name" + item] = formData["name" + item];
    params["deliveryDetail" + item] = formData["deliveryDetail" + item];
    params["content" + item] = formData["content" + item];
  });
  console.log("formData===", formData);
  console.log("specList===", specList);
  console.log("specDataList===", specDataList);
  console.log("params===", params);
  const post = formData.id ? Api.sku_update : Api.sku_add;
  post(params)
    .then((res) => {
      if (res.status === 200) {
        ElMessage.success(i18n.global.t("goodsPublishStore.发布成功"));
        setTimeout(() => {
          releaseStore.step = 0;
          router.push("/manage_product/goods_list");
        }, 1000);
      }
    })
    .finally(() => {
      releaseLoading.value = false;
    });
};

export const initDetailData = (id) => {
  if (!id) return;
  loading.value = true;
  Api.sku_detail(id)
    .then((res) => {
      const { status, data } = res;
      sku.value = data;
      if (status === 200) {
        // 基本信息
        formData.id = data.id;
        formData.skuClassify1Id = data.skuClassify1Id;
        formData.skuClassify2Id = data.skuClassify2Id;
        formData.tenantId = data.tenantId;
        formData.postage = data.postage;
        formData.isFree = data.postage != 0 ? 1 : 0;
        langs.forEach((item) => {
          formData["name" + item] = data["name" + item];
          formData["deliveryDetail" + item] = data["deliveryDetail" + item];
          formData["content" + item] = data["content" + item];
        });
        // 图片处理
        if (data.image) {
          formData.image = data.image;
        }

        if (data.video) {
          formData.video = [
            {
              url: data.video,
              name: i18n.global.t("goodsPublishStore.视频"),
            },
          ];
        }

        if (data.bannerImages) {
          formData.bannerImages = data.bannerImages.split(",");
        }

        // 属性处理
        if (data.attrs && data.attrs.length > 0) {
          formData.attrs = data.attrs.map((item) => item.attributeId);
        }

        // 规格处理
        if (data.specs && data.specs.length > 0) {
          specList.value = data.specs.map((spec, index) => {
            // 设置使用哪个规格的图片
            if (spec.setImage === 1) {
              useImageIndex.value = index;
            }
            const obj = {
              value: spec.specificationId,
              // name: spec.name,
              info: spec.details.map((detail) => {
                const names = {};
                langs.forEach((item) => {
                  names["name" + item] = detail["name" + item];
                });
                return {
                  id: detail.specificationDetailId,
                  // name: detail.name,
                  ...names,
                  images: detail.image
                };
              }),
            };
            langs.forEach((item) => {
              obj["label" + item] = spec["name" + item];
            });
            return obj;
          });
        }

        // 库存价格处理
        if (data.stocks && data.stocks.length > 0) {
          specDataList.value = data.stocks.map((stock) => {
            let item = {
              status: stock.status,
              stock: stock.stock,
              price: stock.price,
              itemCode: stock.itemCode,
              id: `${stock.skuSpecDetail
                .map((spec) => spec.specificationDetailId)
                .join("_")}`,
              stockId: stock.id,
              originalPrice: stock.originalPrice,
            };
            if (stock.flag === 1) {
              flag.value = `${stock.skuSpecDetail
                .map((spec) => spec.specificationDetailId)
                .join("_")}`;
            }
            // 添加规格值
            stock.skuSpecDetail.forEach((spec) => {
              let obj = {
                id: spec.specificationDetailId,
              };
              langs.forEach((item) => {
                obj["name" + item] = spec?.["specDetailName" + item] || "";
              });
              item[`spec_${spec.specificationId}`] = obj;
            });

            return item;
          });
        }

        // 设置当前步骤
        releaseStore.step = 0;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

export const rest = () => {
  // 重置表单数据
  formData.id = null;
  formData.skuClassify1Id = "";
  formData.skuClassify2Id = "";
  formData.tenantId = "";
  formData.attrs = [];
  formData.image = "";
  formData.bannerImages = [];
  formData.isFree = 0;
  formData.postage = 0;
  formData.video = [];

  // 重置多语言字段
  langs.forEach((item) => {
    formData["name" + item] = "";
    formData["deliveryDetail" + item] = "";
    formData["content" + item] = "";
  });

  // 重置其他状态
  sku.value = {};
  specList.value = [];
  useImageIndex.value = 0;
  specDataList.value = [];
  releaseLoading.value = false;
  flag.value = "";
  releaseStore.step = 0;
};
